//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { Button, Card, Checkbox, Divider, Input, List, message, Modal, Space, Spin } from "antd";
import type { LocalRepoInfo } from "@/api/local_repo";
import type { GitStatusItem } from "@/api/git_wrap";
import { run_status, add_to_index, remove_from_index, run_commit } from "@/api/git_wrap";
import { ReloadOutlined } from "@ant-design/icons";
import { ISSUE_STATE_PROCESS, ISSUE_TYPE_TASK, list_my_todo, PROCESS_STAGE_DONE, SORT_KEY_UPDATE_TIME, SORT_TYPE_DSC, update_process_stage, type IssueInfo } from "@/api/project_issue";
import { get_session, get_user_id } from "@/api/user";
import { request } from "@/utils/request";

const PAGE_SIZE = 10;

export interface ChangeFileListProps {
    repo: LocalRepoInfo;
}

const ChangeFileList = (props: ChangeFileListProps) => {
    const [statusList, setStatusList] = useState<GitStatusItem[]>([]);
    const [showModal, setShowModal] = useState(false);
    const [commitMsg, setCommitMsg] = useState("");

    const [inCommit, setInCommit] = useState(false);

    const [issueList, setIssueList] = useState<IssueInfo[]>([]);
    const [totalIssueCount, setTotalIssueCount] = useState(0);
    const [curIssuePage, setCurIssuePage] = useState(0);
    const [selIssueList, setSelIssueList] = useState<IssueInfo[]>([]);

    const [curSessionId, setCurSessionId] = useState("");
    const [curUserId, setCurUserId] = useState("");

    const loadStatus = async () => {
        const tmpList = await run_status(props.repo.path);
        setStatusList(tmpList);
    };


    const addToIndex = async (fileList: string[]) => {
        for (const file of fileList) {
            await add_to_index(props.repo.path, file);
        }
        await loadStatus();
    };

    const removeFromIndex = async (fileList: string[]) => {
        for (const file of fileList) {
            await remove_from_index(props.repo.path, file);
        }
        await loadStatus();
    };


    const runCommit = async () => {
        for (const issue of selIssueList) {
            try {
                await request(update_process_stage({
                    session_id: curSessionId,
                    project_id: issue.project_id,
                    issue_id: issue.issue_id,
                    process_stage: PROCESS_STAGE_DONE,
                }));
            } catch (e) {
                console.log(e);
            }
        }
        try {
            setInCommit(true);
            await run_commit(props.repo.path, commitMsg);
            await loadStatus();
            setShowModal(false);
            message.info("提交成功");
        } finally {
            setInCommit(false);
        }
    };

    const loadUserInfo = async () => {
        const tmpSessionId = await get_session();
        const tmpUserId = await get_user_id();
        setCurSessionId(tmpSessionId);
        setCurUserId(tmpUserId);
    };

    const loadIssueList = async () => {
        if (curSessionId == "" || curUserId == "" || showModal == false) {
            return;
        }
        const res = await request(list_my_todo({
            session_id: curSessionId,
            sort_type: SORT_TYPE_DSC,
            sort_key: SORT_KEY_UPDATE_TIME,
            offset: curIssuePage * PAGE_SIZE,
            limit: PAGE_SIZE,
        }));
        setTotalIssueCount(res.total_count);
        setIssueList(res.info_list);
    };

    useEffect(() => {
        loadStatus();
        loadUserInfo();
    }, []);

    useEffect(() => {
        if (curSessionId != "" && curUserId != "" && showModal) {
            loadIssueList();
        }
    }, [curSessionId, curUserId, curIssuePage, showModal]);

    return (
        <Card title={
            <Space>
                <Checkbox checked={statusList.length > 0 && statusList.filter(item => item.workDirChange).length == 0}
                    indeterminate={statusList.filter(item => item.workDirChange).length > 0 && statusList.filter(item => item.workDirChange).length < statusList.length}
                    onChange={e => {
                        e.stopPropagation();
                        if (e.target.checked) {
                            addToIndex(statusList.map(item => item.path));
                        } else {
                            removeFromIndex(statusList.map(item => item.path));
                        }
                    }} disabled={statusList.length == 0} />
                未提交文件
            </Space>
        } bordered={false} bodyStyle={{ height: "200px", overflowY: "scroll" }}
            headStyle={{ backgroundColor: "#eee" }}
            extra={
                <Space size="middle">
                    <Button type="link" icon={<ReloadOutlined style={{ fontSize: "16px" }} />} title="刷新"
                        onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            loadStatus();
                        }} />
                    <Button type="primary"
                        onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            setCommitMsg("");
                            setShowModal(true);
                        }}
                        disabled={statusList.filter(item => item.workDirChange == false && item.indexChange).length == 0}>提交</Button>

                </Space>
            }>
            <List rowKey="path" dataSource={statusList} pagination={false}
                grid={{ gutter: 16, column: 3 }}
                renderItem={item => (
                    <List.Item>
                        <Space>
                            <Checkbox checked={item.workDirChange == false} onChange={e => {
                                e.stopPropagation();
                                if (e.target.checked) {
                                    addToIndex([item.path]);
                                } else {
                                    removeFromIndex([item.path]);
                                }
                            }} />
                            <span style={{ textDecorationLine: item.workDirDelete ? "overline" : undefined }}>{item.path}</span>
                        </Space>
                    </List.Item>
                )} />
            {showModal == true && (
                <Modal open title="提交变更" mask={false}
                    okText="提交" okButtonProps={{ disabled: commitMsg.trim() == "" || inCommit }}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setShowModal(false);
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        runCommit();
                    }}>
                    <Input.TextArea autoSize={{ minRows: 5, maxRows: 5 }} value={commitMsg} onChange={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setCommitMsg(e.target.value);
                    }} placeholder="请输入变更内容" disabled={inCommit} />
                    {curSessionId != "" && (
                        <>
                            <Divider orientation="left">相关待办工作(转入待检查状态)</Divider>
                            <List rowKey="issue_id" dataSource={issueList} style={{ maxHeight: "calc(100vh - 500px)", overflowY: "scroll" }}
                                pagination={{ pageSize: PAGE_SIZE, total: totalIssueCount, current: curIssuePage + 1, onChange: page => setCurIssuePage(page - 1), hideOnSinglePage: true, showSizeChanger: false }}
                                renderItem={issueItem => (
                                    <List.Item>
                                        <Space>
                                            <Checkbox checked={selIssueList.map(item => item.issue_id).includes(issueItem.issue_id)} disabled={!(issueItem.exec_user_id == curUserId && issueItem.state == ISSUE_STATE_PROCESS)}
                                                onChange={e => {
                                                    e.stopPropagation();
                                                    let tmpList = selIssueList.slice();
                                                    if (tmpList.map(item => item.issue_id).includes(issueItem.issue_id)) {
                                                        tmpList = selIssueList.filter(item => item.issue_id != issueItem.issue_id);
                                                    } else {
                                                        tmpList.push(issueItem);
                                                    }
                                                    setSelIssueList(tmpList);
                                                }} />
                                            {issueItem.issue_type == ISSUE_TYPE_TASK ? "任务" : "缺陷"}:{issueItem.basic_info.title}
                                        </Space>
                                    </List.Item>
                                )} />
                        </>
                    )}
                    {inCommit && (
                        <div style={{ display: "flex", justifyContent: "flex-end", marginTop: "10px" }}>
                            <Spin />
                            &nbsp;提交中......
                        </div>
                    )}
                </Modal>
            )}
        </Card>
    );
};

export default ChangeFileList;